/*
 * @lc app=leetcode.cn id=1305 lang=javascript
 *
 * [1305] 两棵二叉搜索树中的所有元素
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {number[]}
 */
var getNodes = function (root, arr) {
  if (!root) return;
  getNodes(root.left, arr);
  arr.push(root.val);
  getNodes(root.right, arr);
}
var getAllElements = function (root1, root2) {
  let arr1 = [], arr2 = [];
  getNodes(root1, arr1);
  getNodes(root2, arr2);

  let result = [];
  let p1 = 0, p2 = 0, cur = 0;
  while (p1 < arr1.length || p2 < arr2.length) {
    if (p2 >= arr2.length || (p1 < arr1.length && arr1[p1] < arr2[p2])) {
      result[cur++] = arr1[p1++];
    } else {
      result[cur++] = arr2[p2++];
    }
  }
  return result;
};
// @lc code=end

